import { Dropdown, type MenuProps, Modal, Space } from 'antd'
import classNames from 'classnames'
import React, { useState } from 'react'
import styles from '@/app/components/base/markdown/render-widgets/list-item/style/index.module.css'
import Toast from '@/app/components/base/toast'
import { LcSessionStorage } from '@/app/components/bridge/storage'
import { IconSettings } from '@/app/components/chat/xf-voice/Icon'
import { deleteConversation } from '@/service'
import type { ConversationItem } from '@/types/app'

type ConversationItemViewProps = {
  data: ConversationItem[]
  onClear?: () => void
}

export default ({
  data,
  onClear,
}: ConversationItemViewProps) => {
  const deleteCon = async () => {
    try {
      if (!data.length) {
        Toast({
          type: 'info',
          message: '当前还没有会话信息！',
        })
        return
      }
      await Promise.all(data.map(v => deleteConversation(v.id)))
      await LcSessionStorage.getInstance().clear()
      onClear?.()
    }
    catch (e) {
      console.error(e)
      Toast({
        type: 'error',
        message: '清除会话出错了！',
      })
    }
  }
  const handleClick: MenuProps['onClick'] = async (item) => {
    item.domEvent.stopPropagation()
    console.log('Item:', item)
    switch (item.key) {
      case 'DELETE':
        Modal.confirm({
          title: '确认清除所有会话信息？',
          onOk() {
            deleteCon()
          },
          okType: 'danger',
          okText: '确认',
          cancelText: '取消',
        })
        break
    }
  }
  const items: MenuProps['items'] = [
    {
      key: 'DELETE',
      label: <span>清除所有会话</span>,
    },
  ]
  const [isMenuOpen, setIsMenuOpen] = useState(false)
  return (
    <Dropdown menu={{
      items,
      onClick: handleClick,
    }}
    onOpenChange={(open) => {
      setIsMenuOpen(open)
    }}
    >
      <a className={classNames({
        [styles.vs_block]: isMenuOpen,
      })} onClick={e => e.preventDefault()}
      >
        <Space onClick={e => e.preventDefault()}>
          <span className={styles.icon}><IconSettings className="w-[16px] h-[16px]"/></span>
        </Space>
      </a>
    </Dropdown>
  )
}
